package com.zhihaoliang.coroutine.buss.flow.func

import com.zhihaoliang.coroutine.util.log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import kotlin.coroutines.coroutineContext

/**
 * @author 支豪亮
 * @date 2022/10/24 10:33
 * @des 数据流的接受
 */
object FlowIntroduce {

    fun onIntroduce(mainScope: CoroutineScope) = mainScope.launch {
        log("I'm the parent Coroutine", coroutineContext)
        launch {
            for (k in 1..3) {
                log("I'm not blocked $k", coroutineContext)
                delay(2000)
            }
        }
        simple().collect { value -> log(value, coroutineContext) }

        log("I'm the parent Coroutine end")
    }

    private fun simple(): Flow<Int> = flow { // 流构建器
        for (i in 1..3) {
            delay(2000) // 假装我们在这里做了一些有用的事情
            log("I'm not emit $i", coroutineContext)
            emit(i) // 发送下一个值
        }
    }

}